<template>
  <div class="flash-sale">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载秒杀商品中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="loadFlashSaleItems" class="retry-btn">重新加载</button>
    </div>

    <!-- 空状态 -->
    <div v-else-if="items.length === 0" class="empty-container">
      <p>暂无秒杀商品</p>
    </div>

    <!-- 商品列表 -->
    <div v-else class="flash-sale-grid">
      <div
        v-for="item in items"
        :key="item.goods_id"
        class="flash-sale-item"
        @click="goToProductDetail(item.goods_id)"
      >
        <div class="goods-image">
          <img :src="item.goods_cover_img_file || item.goods_cover_img" :alt="item.goods_name" />
        </div>
        <div class="goods-info">
          <h3 class="goods-name">{{ item.goods_name }}</h3>
          <div class="price-section">
            <span class="flash-price">¥{{ item.flash_sale_price }}</span>
            <span class="original-price">¥{{ item.market_price }}</span>
          </div>
          <div class="sale-info">
            <span>已售{{ item.goods_sales }}</span>
            <span>剩余{{ item.flash_sale_stock }}</span>
          </div>
          <div class="time-range">
            {{ formatTime(item.flash_sale_start_time) }} -
            {{ formatTime(item.flash_sale_end_time) }}
          </div>
          <button
            class="buy-btn"
            :class="{ disabled: !isFlashSaleActive(item) }"
            :disabled="!isFlashSaleActive(item)"
            @click.stop="isFlashSaleActive(item) && goToProductDetail(item.goods_id)"
          >
            {{ isFlashSaleActive(item) ? '立即抢购' : '已结束' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import type { PropType } from 'vue'
import { useRouter } from 'vue-router'
import { goodsApi } from '@/api/goods'
import type { FlashSaleItem } from '@/api/goods'

export default defineComponent({
  name: 'FlashSale',
  props: {
    // 可选属性：如果外部传入数据，则不自动加载
    flashSaleItems: {
      type: Array as PropType<FlashSaleItem[]>,
      default: () => [],
    },
    autoLoad: {
      type: Boolean,
      default: true,
    },
  },
  setup(props) {
    const router = useRouter()
    const items = ref<FlashSaleItem[]>(props.flashSaleItems)
    const loading = ref(false)
    const error = ref<string | null>(null)

    // 加载秒杀商品数据
    const loadFlashSaleItems = async () => {
      if (!props.autoLoad || props.flashSaleItems.length > 0) return

      loading.value = true
      error.value = null

      try {
        const response = await goodsApi.getFlashSaleList({
          page_size: 12,
        })
        items.value = response.results
      } catch (err) {
        error.value = '加载秒杀商品失败'
        console.error('Failed to load flash sale items:', err)
      } finally {
        loading.value = false
      }
    }

    // 跳转到商品详情页
    const goToProductDetail = (goodsId: number) => {
      router.push({
        name: 'ProductDetail',
        params: { id: goodsId.toString() },
      })
    }

    onMounted(() => {
      if (props.autoLoad) {
        loadFlashSaleItems()
      }
    })

    return {
      items,
      loading,
      error,
      loadFlashSaleItems,
      goToProductDetail,
    }
  },
  methods: {
    formatTime(timeString: string): string {
      return new Date(timeString).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
      })
    },
    isFlashSaleActive(item: FlashSaleItem): boolean {
      if (!item.is_flash_sale) return false
      const now = new Date()
      const startTime = new Date(item.flash_sale_start_time)
      const endTime = new Date(item.flash_sale_end_time)
      return now >= startTime && now <= endTime && item.flash_sale_stock > 0
    },
  },
})
</script>

<style scoped>
.flash-sale {
  padding: 20px;
}

.flash-sale-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.flash-sale-item {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  background: white;
}

.flash-sale-item:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.goods-image img {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.goods-info {
  padding: 12px;
}

.goods-name {
  font-size: 16px;
  margin: 0 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price-section {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.flash-price {
  color: #f44336;
  font-size: 18px;
  font-weight: bold;
}

.original-price {
  color: #999;
  font-size: 14px;
  text-decoration: line-through;
  margin-left: 8px;
}

.sale-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.time-range {
  font-size: 12px;
  color: #666;
  margin-bottom: 12px;
}

.buy-btn {
  width: 100%;
  padding: 8px 0;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.buy-btn:hover {
  background-color: #e53935;
}

.buy-btn.disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #f44336;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 错误状态样式 */
.error-container {
  text-align: center;
  padding: 40px 20px;
  color: #f44336;
}

.retry-btn {
  margin-top: 12px;
  padding: 8px 16px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.retry-btn:hover {
  background-color: #e53935;
}

/* 空状态样式 */
.empty-container {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}
</style>
